const Redis = require('../redis/Redis')

const getRandom = (start, end, fixed=0) =>{
    return (start + (end - start) * Math.random()).toFixed(fixed)
}

const formatDate = (date, fmt) => {
    date = date || new Date()
    fmt = fmt || 'yyyy/MM/dd hh:ii:ss'
    let o = {
        'M+': date.getMonth() + 1,                   // 月份
        'd+': date.getDate(),                        // 日
        'h+': date.getHours(),                       // 小时
        'i+': date.getMinutes(),                     // 分
        's+': date.getSeconds(),                     // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds()                 // 毫秒
    }

    if (/(y+)/i.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
        }
    }
    return fmt
}

const mySend = (res, code, msg = '失败', body = null) => {
    res.send({code, msg, body})
}

const Vtoken = (token) => {
    return new Promise((resolve, reject) => {
        if(!token){
            resolve(null)
        }
        Redis.get(token, 1).then(result => {
            if(!result){
                resolve(null)
            }else{
                resolve(JSON.parse(result))
            }
            
        }).catch(err => {
            resolve(null)
        })
    })
}

const checkParams = (params) => {
    let str = ''
    for(let prop in params){
        if(params[prop] === undefined || params[prop] === ''){
            str += (prop + ', ')
        }
    }
    return (str ? str + '不能为空' : str)
}

const getQueryObject = (url) => {
    let query = url.split('?')[1]
    let arr = query.split('&')
    let obj = {}
    arr.forEach(item => {
        let keyValue = item.split('=')
        obj[keyValue[0]] = keyValue[1]
    })
    return obj
}

const sleep = (ms) => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve()
        }, ms)
    })
}


module.exports = {
    getRandom, formatDate, mySend, Vtoken, checkParams, getQueryObject, sleep
}